#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void Usage(std::string proc)
{
    std::cout << "\nUsage:\t" << proc << " serverip serverport \n"
              << std::endl;
}
// ./udpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "sockfd create error...  errno:" << errno << "  errstring:" << strerror(errno) << std::endl;
        return 1;
    }
    // 客户端必须bind端口才能进行通信，但是多个软件的使用端口一致会导致冲突，不能自己显式的bind端口
    // 使用connect函数，OS会自动进行分配端口
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = serverport;
    /*  三种字符串转网络序列 */
    //inet_aton(serverip.c_str(),&(server.sin_addr));
    //in_addr_t strip = inet_addr(serverip.c_str());
    inet_pton(AF_INET,serverip.c_str(),&(server.sin_addr));
    int n = connect(sockfd, (struct sockaddr*)&server,sizeof(server));
    if(n < 0)
    {
         std::cout << "connect error...  errno:" << errno << "  errstring:" << strerror(errno) << std::endl;
         return 2;
    }
    std::string message;
    while(true)
    {
        std::cout<<"Please Enter# ";
        getline(std::cin,message);
        write(sockfd,message.c_str(),message.size());
        char inbuffer[4096];
        int n = read(sockfd,inbuffer,sizeof(inbuffer));
        if(n > 0)
        {
            inbuffer[n] = 0;
            std::cout<<inbuffer<<std::endl;
        }
    }
    close(sockfd);
    return 0;
}
